package com.jnks.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.jnks.constant.R;
import com.jnks.mapper.SysUserMapper;
import com.jnks.pojo.domain.dto.User;
import com.jnks.pojo.entity.SysUser;
import com.jnks.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 登录Controller
 */
@Slf4j
@RestController
public class LoginController {

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 登录
     */
    @GetMapping("/login")
    public R login(User user) {

        SysUser sysUser = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, user.getUsername()).eq(SysUser::getStatus, 1));

        if (ObjectUtils.isEmpty(sysUser)) {
            return R.error(null, "请输入正确的用户名!");
        } else if (sysUser.getPassword().equals(user.getPassword())) {
            String token = JwtUtil.createToken(sysUser);
            return R.data(token, "登录成功！生成token！");
        } else if (!sysUser.getPassword().equals(user.getPassword())) {
            return R.error(null, "请输入正确的密码!");
        }

        return null;
    }

    /**
     * 修改密码
     */
    @PostMapping("/updatePassword")
    public R updatePassword(User user, String newPassword) {

        SysUser sysUser = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, user.getUsername()).eq(SysUser::getStatus, 1));

        if (ObjectUtils.isEmpty(sysUser)) {
            return R.error(null, "请输入正确的用户名!");
        } else if (sysUser.getPassword().equals(user.getPassword())) {
            sysUser.setPassword(newPassword);
            sysUserMapper.updateById(sysUser);
            return R.data(null, "密码修改成功！");
        } else if (!sysUser.getPassword().equals(user.getPassword())) {
            return R.error(null, "请输入正确的密码!");
        }

        return null;
    }

}